package com.dldata.devtools30.controller;

import com.alibaba.fastjson.JSON;
import com.dldata.devtools30.businessmodel.SessionUserInfoEntity;
import com.dldata.devtools30.repository.common.DlBaseJdbcTemplate;
import com.dldata.devtools30.utils.*;
import com.dldata.devtools30.utils.baidu.ueditor.ActionEnter;
import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifDirectoryBase;
import com.drew.metadata.exif.ExifIFD0Directory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.*;

/**

 */

@Controller
@RequestMapping(value = "/DevCommFileUpload30")
public class DevCommFileUpload30Controller {

    public static final Random RANDOM = new Random(System.currentTimeMillis());
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    DlBaseJdbcTemplate dlBaseJdbcTemplate;

    /**
     * 图片上传,支持多文件上传，request里面的filesroad参数存放该文件准确存放的表字段信息
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "")
    @ResponseBody
    public String fileUpload(@RequestParam MultipartFile[] uploadfiles, HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, String> filesroadMap = new HashMap<>();
        for (int i = 0; i < uploadfiles.length; i++) {
            MultipartFile multipartFile = uploadfiles[i];
            String filename = multipartFile.getOriginalFilename();
            //获取后缀名称
            String fileNameExt =filename.lastIndexOf(".")>-1?filename.substring(filename.lastIndexOf("."), filename.length()):"";
            String wenjianshangchuan = Public.sysConfig.getProperty("wenjianshangchuan");
            String[] split =StringUtil.isEmptyOrLength0(wenjianshangchuan)?new String[0]:wenjianshangchuan.split(",");
            int num=0;
            for (String s : split) {
                if (fileNameExt.trim().equalsIgnoreCase("."+s)){
                    num++;
                }
            }
            if (num==0&&split.length>0){
                Map resultMap = new HashMap<>();
                resultMap.put("success", false);
                resultMap.put("msg", "不可上传"+fileNameExt.trim()+"格式文件");
                resultMap.put("filename", filename);
                resultMap.put("code",1);//0表示成功，1失败
                return JSON.toJSONString(resultMap);
            }
        }


        String filesroad = request.getParameter("filesroad");
        if (!StringUtil.isNullOrSpace(filesroad) && !StringUtil.isNullOrSpace(filesroad.trim())) {
            String[] filesroadAry = filesroad.split(",");
            for (int i = 0; i < filesroadAry.length; i++) {
                filesroadMap.put(String.valueOf(i), filesroadAry[i]);
            }
        }

        List filenames = new LinkedList<>();
        List filenamesOrg = new LinkedList<>();
        List<File> tmpFiles = new LinkedList<>();
        try {
            for (int i = 0; i < uploadfiles.length; i++) {
                MultipartFile multipartFile = uploadfiles[i];

                //按照当前时间的年和月来创建文件存储路径
                File fileUrl = new File(DateUtil.formatFromDate("yyyyMM", Calendar.getInstance().getTime()));
                //获取根目录
                String templatePath =Public.sysConfig.getProperty(Public.image_dir) + "/";
                //判断是否为空并上传
                if (Util.checkNotNull(multipartFile) && Util.checkNotNull(multipartFile.getOriginalFilename())) {
                    //获取文件名
                    String filenameOrgThis = multipartFile.getOriginalFilename();
                    filenamesOrg.add(filenameOrgThis);
//                    String tmpFolder=System.getProperty("java.io.tmpdir");
                    File tmpFile=new File(templatePath,System.currentTimeMillis()+"_"+ RANDOM.nextLong()+"_tmp");
                    multipartFile.transferTo(tmpFile);
                    tmpFiles.add(tmpFile);

//                        String fileName = filename.substring(0,  filename.lastIndexOf("."));
                    FileInputStream fileInputStream = new FileInputStream(tmpFile);
                    String fileName ="";
                    try{
                        fileName = MD5Util.MD5Encoder(fileInputStream);
                    }finally{
                        fileInputStream.close();
                    }

                    //获取后缀名称
                    String fileNameExt =filenameOrgThis.lastIndexOf(".")>-1?filenameOrgThis.substring(filenameOrgThis.lastIndexOf("."), filenameOrgThis.length()):"";
                    String uploadfilerename = Public.sysConfig.getProperty(Public.uploadfilerename);
                    if(StringUtil.isEmptyOrLength0(uploadfilerename) || "0".equalsIgnoreCase(uploadfilerename)){
                        fileName=filenameOrgThis.lastIndexOf(".")>-1?filenameOrgThis.substring(0,filenameOrgThis.lastIndexOf(".")):filenameOrgThis;
                    }
                    String filesroad1 =StringUtil.isEmptyOrLength0(filesroadMap.get(String.valueOf(i)))?filesroadMap.get(String.valueOf(i)) : "default";
                    if (fileNameExt.equalsIgnoreCase(".jpg") || fileNameExt.equalsIgnoreCase(".jpeg") || fileNameExt.equalsIgnoreCase(".png") || fileNameExt.equalsIgnoreCase(".gif") || fileNameExt.equalsIgnoreCase(".bmp")) {
                        String fileUriImg = fileUrl.getPath() + "/img/";
                        String filePath = Util.saveFile(templatePath, fileUriImg, fileName, fileNameExt, request, tmpFile, filesroad1);
                        filePath = filePath.replaceAll("\\\\", "/");
                        filenames.add(filePath);
                    } else if (fileNameExt.equalsIgnoreCase(".amr") || fileNameExt.equalsIgnoreCase(".mp3") || fileNameExt.equalsIgnoreCase(".mp4") || fileNameExt.equalsIgnoreCase(".ogg") || fileNameExt.equalsIgnoreCase(".acc") || fileNameExt.equalsIgnoreCase(".wav")) {
                        String fileUriAudio = fileUrl.getPath() + "/audio/";
                        String filePath = Util.saveFile(templatePath, fileUriAudio, fileName, fileNameExt, request, tmpFile, filesroad1);
                        filePath = filePath.replaceAll("\\\\", "/");
                        filenames.add(filePath);
                    } else{
                        String fileUriOther = fileUrl.getPath() + "/other/";
                        String filePath = Util.saveFile(templatePath, fileUriOther, fileName, fileNameExt, request, tmpFile, filesroad1);
                        filePath = filePath.replaceAll("\\\\", "/");
                        filenames.add(filePath);
                    }
                    tmpFile.delete();
                }
            }

            for (int i = 0; i < tmpFiles.size(); i++) {
                File tmpFile = tmpFiles.get(i);
                if(tmpFile!=null&&tmpFile.exists()){
                    tmpFile.delete();
                }
            }

            //返回全路径数据
            Map resultMap = new HashMap<>();
            resultMap.put("success", true);
            resultMap.put("msg", "上传成功.");
            resultMap.put("filename", filenames);
            resultMap.put("filenamesOrg", filenamesOrg);
            resultMap.put("code",0);//0表示成功，1失败
            resultMap.put("msg","上传成功");//提示消息

            List filenamesrcs = new ArrayList();
            for (int i = 0; i < filenames.size(); i++) {
                String filenamedest = (String) filenames.get(i);
                String property = Public.sysConfig.getProperty(Public.image_url);
                filenamesrcs.add(property.endsWith("/")?(property+filenamedest):(property+"/"+filenamedest));
            }
            resultMap.put("filenamesrcs", filenamesrcs);

            HashMap dataMap=new HashMap();
            resultMap.put("data",dataMap);
            dataMap.put("src",Public.sysConfig.getProperty(Public.image_url)+"/"+filenames.get(0));//图片url
            dataMap.put("title","");//图片名称，这个会显示在输入框里

            return JSON.toJSONString(resultMap);

        } catch (Exception ex) {
            logger.error("【执行" + this.getClass().getName() + ".saveFile() 方法失败 】异常：" + ex.getMessage(), ex);
            Map resultMap = new HashMap<>();
            resultMap.put("success", false);
            resultMap.put("msg", "系统错误，请稍候再试." + ex.getMessage());
            resultMap.put("filename", filenames);
            resultMap.put("filenamesOrg", filenamesOrg);
            resultMap.put("code",1);//0表示成功，1失败

            return JSON.toJSONString(resultMap);
        }

    }

    /**
     * 图片上传,支持多文件上传，request里面的filesroad参数存放该文件准确存放的表字段信息
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "imageStream")
    @ResponseBody
    public String imageStream(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<MultipartFile> multipartFileList = getMultipartFileList(request);
        Map<String, String> filesroadMap = new HashMap<>();
        for (int i = 0; i < multipartFileList.size(); i++) {
            MultipartFile multipartFile = multipartFileList.get(i);
            String filename = multipartFile.getOriginalFilename();
            //获取后缀名称
            String fileNameExt =filename.lastIndexOf(".")>-1?filename.substring(filename.lastIndexOf("."), filename.length()):"";
            String[] split = Public.sysConfig.getProperty("wenjianshangchuan").split(",");
            int num=0;
            for (String s : split) {
                if (fileNameExt.trim().equalsIgnoreCase("."+s)){
                    num++;
                }
            }
            if (num==0){
                Map resultMap = new HashMap<>();
                resultMap.put("success", false);
                resultMap.put("msg", "不可上传"+fileNameExt.trim()+"格式文件");
                resultMap.put("filename", filename);
                resultMap.put("code",1);//0表示成功，1失败

                return JSON.toJSONString(resultMap);
            }
        }

        String imageStream1 = request.getParameter("imageStream");
        if (StringUtil.isEmptyOrLength0(imageStream1)) {
            Map resultMap = new HashMap<>();
            resultMap.put("success", false);
            resultMap.put("msg", "imageStream为空");
            resultMap.put("filename", new LinkedList<>());
            return JSON.toJSONString(resultMap);
        }

//     音频 audio wav
//           png
        String type = request.getParameter("type");

        imageStream1 = imageStream1.substring(imageStream1.indexOf("base64,") + 7);
        System.gc();
        byte[] fileData = org.apache.commons.codec.binary.Base64.decodeBase64(imageStream1);
//        byte[] fileData= org.apache.commons.codec.binary.Base64.decodeBase64(base64Stream);
        logger.info("base64Stream.length: " + imageStream1.length() + "  fileData: " + fileData.length);
        imageStream1 = null;
        System.gc();

        String filesroad = request.getParameter("filesroad");
        if (!StringUtil.isNullOrSpace(filesroad) && !StringUtil.isNullOrSpace(filesroad.trim())) {
            String[] filesroadAry = filesroad.split(",");
            for (int i = 0; i < filesroadAry.length; i++) {
                filesroadMap.put(String.valueOf(i), filesroadAry[i]);
            }
        }

        List filenames = new LinkedList<>();
        try {
            //按照当前时间的年和月来创建文件存储路径
            String fileUrl = DateUtil.formatFromDate("yyyyMM", Calendar.getInstance().getTime());
            //获取根目录
            String templatePath = Public.sysConfig.getProperty(Public.image_dir)  + "/";
            String fileName = MD5Util.MD5Encoder(fileData);
            String filesroad1 = filesroadMap.keySet().size() > 0 ? filesroadMap.get(0) : "default";
            if (type == null || !type.equals("audio")) {
                Metadata metadata = ImageMetadataReader.readMetadata(new ByteArrayInputStream(fileData));
                Directory exif = metadata.getFirstDirectoryOfType(ExifDirectoryBase.class);
                String typeORIENTATION = exif == null ? null : exif.getString(ExifDirectoryBase.TAG_ORIENTATION);
                logger.info("typeORIENTATION: " + typeORIENTATION);
                exif = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
                typeORIENTATION = exif == null ? null : exif.getString(ExifIFD0Directory.TAG_ORIENTATION);
                logger.info("typeORIENTATION: " + typeORIENTATION);
                //图片正常情况下
                if (!StringUtil.isEmptyOrLength0(typeORIENTATION)) {//判断拍摄方向是否为空
                    switch (Integer.parseInt(typeORIENTATION)) {
                        //要进行180度旋转
                        case 3: {
                            fileData = rotateImg(fileData, 180.0, "jpg");
                            break;
                        }
                        //要进行90度旋转
                        case 6: {
                            fileData = rotateImg(fileData, 90.0, "jpg");
                            break;
                        }
                        //要进行-90度旋转
                        case 8: {
                            fileData = rotateImg(fileData, -90.0, "jpg");
                            break;
                        }
                        default:
                            break;
                    }
                }
                String accessFileUrl = "/" + fileUrl + "/img/" + filesroad1 + "/" + fileName + ".jpg";
                String filePathWuli = templatePath + accessFileUrl;
                File destFile = new File(filePathWuli);
                if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }
                FileUtils.writeByteArrayToFile(destFile, fileData, false);
                accessFileUrl = accessFileUrl.replaceAll("\\\\", "/");
                filenames.add(accessFileUrl);
            } else {
                String accessFileUrl = "/" + fileUrl + "/img/" + filesroad1 + "/" + fileName + ".wav";
                String filePathWuli = templatePath + accessFileUrl;
                File destFile = new File(filePathWuli);
                if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }
                FileUtils.writeByteArrayToFile(destFile, fileData, false);
                accessFileUrl = accessFileUrl.replaceAll("\\\\", "/");
                filenames.add(accessFileUrl);
            }
            fileData = null;
            System.gc();
            //返回全路径数据
            Map resultMap = new HashMap<>();
            resultMap.put("success", true);
            resultMap.put("msg", "上传成功.");
            resultMap.put("filename", filenames);

            return JSON.toJSONString(resultMap);

        } catch (Exception ex) {
            logger.error("【执行" + this.getClass().getName() + ".saveFile() 方法失败 】异常：" + ex.getMessage(), ex);
            Map resultMap = new HashMap<>();
            resultMap.put("success", false);
            resultMap.put("msg", "系统错误，请稍候再试.");
            resultMap.put("filename", filenames);

            return JSON.toJSONString(resultMap);
        }


    }


    /**
     * 获取当前请求中的文件列表
     *
     * @param request
     * @return
     */
    protected List<MultipartFile> getMultipartFileList(
            HttpServletRequest request) {
        List<MultipartFile> files = new ArrayList<MultipartFile>();
        try {
            if (request instanceof MultipartHttpServletRequest) {
                // 将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multiRequest.getFileNames();
                // 检查form中是否有enctype="multipart/form-data"
                if (iter.hasNext()) {
                    // 获取multiRequest 中所有的文件名
                    while (iter.hasNext()) {
                        // 一次遍历所有文件
                        // MultipartFile file =
                        // multiRequest.getFile(iter.next().toString());
                        // if (file != null) {
                        // files.add(file);
                        // }
                        // 适配名字重复的文件
                        List<MultipartFile> fileRows = multiRequest
                                .getFiles(iter.next().toString());
                        if (fileRows != null && fileRows.size() != 0) {
                            for (MultipartFile file : fileRows) {
                                if (file != null && !file.isEmpty()) {
                                    files.add(file);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            logger.error("解析MultipartRequest错误", ex);
        }
        return files;
    }




    /**
     * @param bytes
     * @param angle
     * @param format
     * @return
     * @throws Exception
     * @功能:矫正图片旋转，返回byte[]
     */
    public static byte[] rotateImg(byte[] bytes, double angle, String format) {
        try {
            InputStream input = new ByteArrayInputStream(bytes);
            BufferedImage old_img = (BufferedImage) ImageIO.read(input);

            int iw = old_img.getWidth();//原始图象的宽度
            int ih = old_img.getHeight();//原始图象的高度
            angle = angle % 360;
            //将角度转换到0-360度之间
            angle = angle < 0 ? (360 + angle) : angle;
            double ang = Math.toRadians(angle);//将角度转为弧度


            int w = 0;
            int h = 0;
            /**
             *确定旋转后的图象的高度和宽度
             */
            if (angle == 180 || angle == 0 || angle == 360) {
                w = iw;
                h = ih;
            } else if (angle == 90 || angle == 270) {
                w = ih;
                h = iw;
            } else {
                int d = iw + ih;
                w = (int) (d * Math.abs(Math.cos(ang)));
                h = (int) (d * Math.abs(Math.sin(ang)));
            }


            int x = 0;
            int y = 0;
            x = (w / 2) - (iw / 2);//确定原点坐标
            y = (h / 2) - (ih / 2);
            BufferedImage new_img = new BufferedImage(w, h, old_img.getType());
            Graphics2D gs = (Graphics2D) new_img.getGraphics();
//            Color bgcolor=null;
//            if(bgcolor==null){
//                new_img  = gs.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
//            }else{
//                gs.setColor(bgcolor);
//                gs.fillRect(0, 0, w, h);//以给定颜色绘制旋转后图片的背景
//            }

            AffineTransform at = new AffineTransform();
            at.rotate(ang, w / 2, h / 2);//旋转图象
            at.translate(x, y);
            AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
            op.filter(old_img, new_img);
            //新建流。
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //利用ImageIO类的write方法，将BufferedImage以png图片的数据模式写入流。
            ImageIO.write(new_img, format, baos);
            return baos.toByteArray();
        } catch (IOException e) {
            return bytes;
        }
    }

    /**
     * ueeditorupload
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "ueupload")
    public void ueupload(HttpServletRequest request, HttpServletResponse response) throws Exception {

        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html");
        String rootPath = request.getServletContext().getRealPath("/");
        response.getWriter().write(new ActionEnter(request, rootPath).exec());
    }


    @RequestMapping(value = "/toFileUpload")
    public String toDynimic(@RequestParam Map<String, Object> paramMap,ModelMap model,HttpServletRequest request, HttpServletResponse response)throws Exception {
        SessionUserInfoEntity sessionUserInfoEntity = RightUtil.getCurrentUser(request);
        if (StringUtil.isEmptyOrLength0(sessionUserInfoEntity.getDevtooluser())) {
            return "";
        }
        Map<String, String[]> paraMap = request.getParameterMap();
        for (Iterator iterator = paraMap.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, String[]> next = (Map.Entry<String, String[]>) iterator.next();
            if (!StringUtil.isEmptyOrLength0(next.getValue())) {
                request.setAttribute(next.getKey(), StringUtils.join(next.getValue(), ","));
            }
        }
        model.addAttribute("paramMap",paramMap);
        return "thymeleaf/devtools30/common/vCommonFileUpload";
    }

    /**
     * 图片上传,支持多文件上传，request里面的filesroad参数存放该文件准确存放的表字段信息
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "dbfileUpload")
    @ResponseBody
    public String dbfileUpload(@RequestParam MultipartFile[] uploadfiles, HttpServletRequest request, HttpServletResponse response){
        Map<String, String> filesroadMap = new HashMap<>();
        for (int i = 0; i < uploadfiles.length; i++) {
            MultipartFile multipartFile = uploadfiles[i];
            String filename = multipartFile.getOriginalFilename();
            //获取后缀名称
            String fileNameExt =filename.lastIndexOf(".")>-1?filename.substring(filename.lastIndexOf(".")+1, filename.length()):"";
            String wenjianshangchuan = Public.sysConfig.getProperty("wenjianshangchuan");
            String[] split =StringUtil.isEmptyOrLength0(wenjianshangchuan)?new String[0]:wenjianshangchuan.split(",");
            int num=0;
            for (String s : split) {
                if (fileNameExt.trim().equalsIgnoreCase(s)){
                    num++;
                }
            }
            if (num==0){
                Map resultMap = new HashMap<>();
                resultMap.put("success", false);
                resultMap.put("msg", "不可上传"+fileNameExt.trim()+"格式文件");
                resultMap.put("filename", filename);
                resultMap.put("code",1);//0表示成功，1失败

                return JSON.toJSONString(resultMap);
            }
        }

        List filenames = new LinkedList<>();
        List filenamesOrg = new LinkedList<>();
        Connection connection = null;
        try {
            connection = dlBaseJdbcTemplate.getDataSource().getConnection();

            for (int i = 0; i < uploadfiles.length; i++) {
                MultipartFile multipartFile = uploadfiles[i];
                //判断是否为空并上传
                if (Util.checkNotNull(multipartFile) && Util.checkNotNull(multipartFile.getOriginalFilename())) {
                    String dataId = UUID.randomUUID().toString();
                    StringBuilder sqlbuilder=new StringBuilder();
                    sqlbuilder.append(" insert into sys_crf_form_file (");
                    sqlbuilder.append(" id,datacontent,fileNameOrg,fileLength,contentType");
                    sqlbuilder.append(" ) values (");
                    sqlbuilder.append(" ?,?,?,?,?");
                    sqlbuilder.append(" )");
                    PreparedStatement preparedStatement = connection.prepareStatement(sqlbuilder.toString());
                    preparedStatement.setString(1, dataId);
                    preparedStatement.setBinaryStream(2, multipartFile.getInputStream());
                    preparedStatement.setString(3, multipartFile.getOriginalFilename());
                    preparedStatement.setLong(4, multipartFile.getSize());
                    preparedStatement.setString(5, multipartFile.getContentType());
                    preparedStatement.execute();
                    preparedStatement.close();;
                    filenames.add(dataId);
                    filenamesOrg.add(multipartFile.getOriginalFilename());
                }
            }

            //返回全路径数据
            Map resultMap = new HashMap<>();
            resultMap.put("success", true);
            resultMap.put("msg", "上传成功.");
            resultMap.put("filename", filenames);
            resultMap.put("filenameorg", filenamesOrg);
            return JSON.toJSONString(resultMap);

        } catch (Exception ex) {
            logger.error("【执行" + this.getClass().getName() + ".saveFile() 方法失败 】异常：" + ex.getMessage(), ex);
            Map resultMap = new HashMap<>();
            resultMap.put("success", false);
            resultMap.put("msg", "系统错误，请稍候再试." + ex.getMessage().replace("\r", "").replace("\n", ""));
            resultMap.put("filename", filenames);
            resultMap.put("filenameorg", filenamesOrg);

            return JSON.toJSONString(resultMap);
        } finally {
            DataSourceUtils.releaseConnection(connection,dlBaseJdbcTemplate.getDataSource());
        }

    }

    /**
     * 文件资源获取
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "getDbFileProperty")
    @ResponseBody
    public Map getDbFileProperty(HttpServletRequest request, HttpServletResponse response,String dataId){
        try {
            StringBuilder sqlbuilder=new StringBuilder();
            sqlbuilder.append(" select id,fileNameOrg,fileLength ");
            sqlbuilder.append(" from sys_crf_form_file ");
            sqlbuilder.append(" where id = ?  ");

            List<Map<String, Object>> dataList=dlBaseJdbcTemplate.queryForList(sqlbuilder.toString(), new Object[]{dataId});
            Map resultMap = new HashMap<>();
            resultMap.put("success", true);
            resultMap.put("fileProp",dataList.size()>0?dataList.get(0):"");
            return resultMap;
        } catch (Exception ex) {
            logger.error("【执行" + this.getClass().getName() + ".saveFile() 方法失败 】异常：" + ex.getMessage(), ex);
            Map resultMap = new HashMap<>();
            resultMap.put("success", false);
            resultMap.put("msg", "系统错误，请稍候再试." + ex.getMessage().replace("\r", "").replace("\n", ""));
            return resultMap;
        }
    }


    /**
     * 文件资源获取
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "getDbFileData")
    public void getFileData(HttpServletRequest request, HttpServletResponse response,String dataId){
        Connection connection = null;
        try {
            connection = dlBaseJdbcTemplate.getDataSource().getConnection();
            StringBuilder sqlbuilder=new StringBuilder();
            sqlbuilder.append(" select fileNameOrg,contentType,fileLength,datacontent ");
            sqlbuilder.append(" from sys_crf_form_file ");
            sqlbuilder.append(" where id=? ");
            PreparedStatement preparedStatement = connection.prepareStatement(sqlbuilder.toString());
            preparedStatement.setString(1, dataId);
            ResultSet rst= preparedStatement.executeQuery();
            if (rst.next()){
                String  contentType=rst.getString("contentType");
                response.setContentType(StringUtil.isEmptyOrLength0(contentType)?"application/octet-stream":contentType);
                String  inputStreamFileName=rst.getString("fileNameOrg");
                long  fileLength=rst.getLong("fileLength");
                if(!StringUtil.isEmptyOrLength0(request.getParameter("gettype"))&&"download".equalsIgnoreCase(request.getParameter("gettype"))){
                    response.addHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(inputStreamFileName,"UTF-8"));
                }
//                response.addHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(inputStreamFileName,"UTF-8"));
                InputStream inputStream=rst.getBinaryStream("datacontent");
                byte[] byteData=new byte[1024*1024*3];
                int count=-1;
                ServletOutputStream servletOutputStream= response.getOutputStream();
                while ((count=inputStream.read(byteData))!=-1){
                    servletOutputStream.write(byteData,0,count);
                }
                servletOutputStream.flush();
            }
        } catch (Exception ex) {
            logger.error("【执行" + this.getClass().getName() + ".saveFile() 方法失败 】异常：" + ex.getMessage(), ex);
            response.setStatus(503);
            response.setHeader("errorinfo","system error.");
        } finally {
            DataSourceUtils.releaseConnection(connection,dlBaseJdbcTemplate.getDataSource());
        }

    }


    /**
     * 图片上传,支持多文件上传，request里面的filesroad参数存放该文件准确存放的表字段信息
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/layuiupload")
    @ResponseBody
    public String layuiupload(@RequestParam MultipartFile[] file, HttpServletRequest request, HttpServletResponse response) throws Exception {

        Map<String, String> filesroadMap = new HashMap<>();
        for (int i = 0; i < file.length; i++) {
            MultipartFile multipartFile = file[i];
            String filename = multipartFile.getOriginalFilename();
            //获取后缀名称
            String fileNameExt =filename.lastIndexOf(".")>-1?filename.substring(filename.lastIndexOf("."), filename.length()):"";
            String wenjianshangchuan = Public.sysConfig.getProperty("wenjianshangchuan");
            String[] split =StringUtil.isEmptyOrLength0(wenjianshangchuan)?new String[0]:wenjianshangchuan.split(",");
            int num=0;
            for (String s : split) {
                if (fileNameExt.trim().equalsIgnoreCase("."+s)){
                    num++;
                }
            }
            if (num==0){
                Map resultMap = new HashMap<>();
                resultMap.put("success", false);
                resultMap.put("msg", "不可上传"+fileNameExt.trim()+"格式文件");
                resultMap.put("filename", filename);
                resultMap.put("code",1);//0表示成功，1失败

                return JSON.toJSONString(resultMap);
            }
        }


        String filesroad = request.getParameter("filesroad");
        if (!StringUtil.isNullOrSpace(filesroad) && !StringUtil.isNullOrSpace(filesroad.trim())) {
            String[] filesroadAry = filesroad.split(",");
            for (int i = 0; i < filesroadAry.length; i++) {
                filesroadMap.put(String.valueOf(i), filesroadAry[i]);
            }
        }

        List filenames = new LinkedList<>();
        List<File> tmpFiles = new LinkedList<>();
        try {
            for (int i = 0; i < file.length; i++) {
                MultipartFile multipartFile = file[i];

                //按照当前时间的年和月来创建文件存储路径
                File fileUrl = new File(DateUtil.formatFromDate("yyyyMM", Calendar.getInstance().getTime()));
                //获取根目录
                String templatePath = Public.sysConfig.getProperty(Public.image_dir)  + "/";
                //判断是否为空并上传
                if (Util.checkNotNull(multipartFile) && Util.checkNotNull(multipartFile.getOriginalFilename())) {
                    //获取文件名
                    String filename = multipartFile.getOriginalFilename();

                    String tmpFolder=System.getProperty("java.io.tmpdir");
                    String fileName = MD5Util.MD5Encoder(new ByteArrayInputStream(multipartFile.getBytes()));

                    //获取后缀名称
                    String fileNameExt =filename.lastIndexOf(".")>-1?filename.substring(filename.lastIndexOf("."), filename.length()):"";

                    String filesroad1 =StringUtil.isEmptyOrLength0(filesroadMap.get(String.valueOf(i)))?filesroadMap.get(String.valueOf(i)) : "default";
                    if (fileNameExt.equalsIgnoreCase(".jpg") || fileNameExt.equalsIgnoreCase(".jpeg") || fileNameExt.equalsIgnoreCase(".png") || fileNameExt.equalsIgnoreCase(".gif") || fileNameExt.equalsIgnoreCase(".bmp")) {
                        String fileUriImg = fileUrl.getPath() + "/img/";
                        String filePath = Util.saveFile(templatePath, fileUriImg, fileName, fileNameExt, request, multipartFile, filesroad1);
                        filePath = filePath.replaceAll("\\\\", "/");
                        filenames.add(filePath);
                    } else if (fileNameExt.equalsIgnoreCase(".amr") || fileNameExt.equalsIgnoreCase(".mp3") || fileNameExt.equalsIgnoreCase(".mp4") || fileNameExt.equalsIgnoreCase(".ogg") || fileNameExt.equalsIgnoreCase(".acc") || fileNameExt.equalsIgnoreCase(".wav")) {
                        String fileUriAudio = fileUrl.getPath() + "/audio/";
                        String filePath = Util.saveFile(templatePath, fileUriAudio, fileName, fileNameExt, request, multipartFile, filesroad1);
                        filePath = filePath.replaceAll("\\\\", "/");
                        filenames.add(filePath);
                    } else{
                        String fileUriOther = fileUrl.getPath() + "/other/";
                        String filePath = Util.saveFile(templatePath, fileUriOther, fileName, fileNameExt, request, multipartFile, filesroad1);
                        filePath = filePath.replaceAll("\\\\", "/");
                        filenames.add(filePath);
                    }

                }
            }

            for (int i = 0; i < tmpFiles.size(); i++) {
                File tmpFile = tmpFiles.get(i);
                if(tmpFile!=null&&tmpFile.exists()){
                    tmpFile.delete();
                }
            }

            //返回全路径数据
            Map resultMap = new HashMap<>();
            resultMap.put("success", true);
            resultMap.put("msg", "上传成功.");
            resultMap.put("filename", filenames);

            resultMap.put("code",0);//0表示成功，1失败
            resultMap.put("msg","上传成功");//提示消息
            HashMap dataMap=new HashMap();
            resultMap.put("data",dataMap);
            dataMap.put("src",Public.sysConfig.getProperty(Public.image_url)+"/"+filenames.get(0));//图片url
            dataMap.put("title","");//图片名称，这个会显示在输入框里

            return JSON.toJSONString(resultMap);

        } catch (Exception ex) {
            logger.error("【执行" + this.getClass().getName() + ".saveFile() 方法失败 】异常：" + ex.getMessage(), ex);
            Map resultMap = new HashMap<>();
            resultMap.put("success", false);
            resultMap.put("msg", "系统错误，请稍候再试." + ex.getMessage().replace("\r", "").replace("\n", ""));
            resultMap.put("filename", filenames);
            resultMap.put("code",1);//0表示成功，1失败

            return JSON.toJSONString(resultMap);
        }

    }
}
